<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Py2SO - Python转二进制模块工具</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        success: '#52C41A',
                        warning: '#FAAD14',
                        danger: '#FF4D4F',
                        dark: '#1D2129',
                        'dark-2': '#4E5969',
                        'light-1': '#F2F3F5',
                        'light-2': '#E5E6EB',
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                    boxShadow: {
                        'card': '0 4px 16px rgba(0, 0, 0, 0.08)',
                        'card-hover': '0 8px 24px rgba(0, 0, 0, 0.12)',
                    }
                },
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-shadow {
                text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            }
            .transition-height {
                transition: max-height 0.3s ease-in-out;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .gradient-bg {
                background: linear-gradient(135deg, #165DFF 0%, #36CFC9 100%);
            }
        }
    </style>
</head>
<body class="font-inter bg-gray-50 text-dark min-h-screen flex flex-col">
    <!-- 顶部导航 -->
    <header class="bg-white shadow-sm sticky top-0 z-50 transition-all duration-300" id="main-header">
        <div class="container mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center py-4">
                <div class="flex items-center space-x-2">
                    <div class="w-10 h-10 rounded-lg gradient-bg flex items-center justify-center">
                        <i class="fa fa-cogs text-white text-xl"></i>
                    </div>
                    <h1 class="text-xl font-bold text-dark">Py2SO <span class="text-primary text-sm font-normal">v1.0.0</span></h1>
                </div>
                
                <nav class="hidden md:flex items-center space-x-8">
                    <a href="#features" class="text-dark-2 hover:text-primary transition-colors">功能</a>
                    <a href="#compiler" class="text-dark-2 hover:text-primary transition-colors">编译器</a>
                    <a href="#history" class="text-dark-2 hover:text-primary transition-colors">历史记录</a>
                    <a href="#help" class="text-dark-2 hover:text-primary transition-colors">帮助</a>
                </nav>
                
                <div class="flex items-center space-x-4">
                    <button id="theme-toggle" class="p-2 rounded-full hover:bg-light-1 transition-colors">
                        <i class="fa fa-moon-o text-dark-2"></i>
                    </button>
                    <button class="md:hidden p-2 rounded-full hover:bg-light-1 transition-colors" id="mobile-menu-button">
                        <i class="fa fa-bars text-dark-2"></i>
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 移动端菜单 -->
        <div id="mobile-menu" class="hidden md:hidden bg-white border-t border-light-2">
            <div class="container mx-auto px-4 py-3 space-y-3">
                <a href="#features" class="block py-2 text-dark-2 hover:text-primary transition-colors">功能</a>
                <a href="#compiler" class="block py-2 text-dark-2 hover:text-primary transition-colors">编译器</a>
                <a href="#history" class="block py-2 text-dark-2 hover:text-primary transition-colors">历史记录</a>
                <a href="#help" class="block py-2 text-dark-2 hover:text-primary transition-colors">帮助</a>
            </div>
        </div>
    </header>

    <!-- 主要内容 -->
    <main class="flex-grow">
        <!-- 英雄区域 -->
        <section class="bg-gradient-to-br from-primary/5 to-secondary/5 py-16 md:py-24">
            <div class="container mx-auto px-4 sm:px-6 lg:px-8">
                <div class="max-w-3xl mx-auto text-center">
                    <h2 class="text-[clamp(2rem,5vw,3.5rem)] font-bold text-dark leading-tight mb-6 text-shadow">
                        将Python文件转换为<br class="md:hidden">二进制模块
                    </h2>
                    <p class="text-lg md:text-xl text-dark-2 mb-8">
                        简单、高效地将Python代码(.py)编译为跨平台的二进制模块(.so/.pyd)，保护您的源代码
                    </p>
                    <div class="flex flex-col sm:flex-row justify-center gap-4">
                        <a href="#compiler" class="bg-primary hover:bg-primary/90 text-white font-medium py-3 px-8 rounded-lg transition-all shadow-lg hover:shadow-primary/20 hover:-translate-y-0.5">
                            开始编译
                        </a>
                        <a href="#features" class="bg-white hover:bg-light-1 text-dark font-medium py-3 px-8 rounded-lg transition-all shadow-md hover:shadow-lg hover:-translate-y-0.5">
                            了解更多 <i class="fa fa-arrow-right ml-2"></i>
                        </a>
                    </div>
                </div>
            </div>
        </section>
        
        <!-- 功能特点 -->
        <section id="features" class="py-16 bg-white">
            <div class="container mx-auto px-4 sm:px-6 lg:px-8">
                <div class="text-center mb-16">
                    <h2 class="text-3xl font-bold mb-4">强大功能，简单操作</h2>
                    <p class="text-dark-2 max-w-2xl mx-auto">Py2SO提供了丰富的功能，满足您将Python代码编译为二进制模块的各种需求</p>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                    <!-- 功能卡片 1 -->
                    <div class="bg-white rounded-xl shadow-card hover:shadow-card-hover p-6 transition-all duration-300 hover:-translate-y-1">
                        <div class="w-12 h-12 rounded-lg bg-primary/10 flex items-center justify-center mb-4">
                            <i class="fa fa-files-o text-primary text-xl"></i>
                        </div>
                        <h3 class="text-xl font-semibold mb-3">批量处理</h3>
                        <p class="text-dark-2">支持同时上传和编译多个Python文件，大幅提高工作效率，节省时间成本。</p>
                    </div>
                    
                    <!-- 功能卡片 2 -->
                    <div class="bg-white rounded-xl shadow-card hover:shadow-card-hover p-6 transition-all duration-300 hover:-translate-y-1">
                        <div class="w-12 h-12 rounded-lg bg-primary/10 flex items-center justify-center mb-4">
                            <i class="fa fa-sliders text-primary text-xl"></i>
                        </div>
                        <h3 class="text-xl font-semibold mb-3">高级配置</h3>
                        <p class="text-dark-2">提供多种编译选项，包括优化级别、Python版本选择和输出路径自定义等。</p>
                    </div>
                    
                    <!-- 功能卡片 3 -->
                    <div class="bg-white rounded-xl shadow-card hover:shadow-card-hover p-6 transition-all duration-300 hover:-translate-y-1">
                        <div class="w-12 h-12 rounded-lg bg-primary/10 flex items-center justify-center mb-4">
                            <i class="fa fa-desktop text-primary text-xl"></i>
                        </div>
                        <h3 class="text-xl font-semibold mb-3">跨平台支持</h3>
                        <p class="text-dark-2">支持Windows、Linux和macOS系统，生成对应平台的二进制模块文件。</p>
                    </div>
                    
                    <!-- 功能卡片 4 -->
                    <div class="bg-white rounded-xl shadow-card hover:shadow-card-hover p-6 transition-all duration-300 hover:-translate-y-1">
                        <div class="w-12 h-12 rounded-lg bg-primary/10 flex items-center justify-center mb-4">
                            <i class="fa fa-history text-primary text-xl"></i>
                        </div>
                        <h3 class="text-xl font-semibold mb-3">历史记录</h3>
                        <p class="text-dark-2">自动保存编译历史，方便查看过往操作和重新下载已编译的文件。</p>
                    </div>
                    
                    <!-- 功能卡片 5 -->
                    <div class="bg-white rounded-xl shadow-card hover:shadow-card-hover p-6 transition-all duration-300 hover:-translate-y-1">
                        <div class="w-12 h-12 rounded-lg bg-primary/10 flex items-center justify-center mb-4">
                            <i class="fa fa-shield text-primary text-xl"></i>
                        </div>
                        <h3 class="text-xl font-semibold mb-3">源码保护</h3>
                        <p class="text-dark-2">将Python源代码编译为二进制文件，有效保护知识产权，防止代码泄露。</p>
                    </div>
                    
                    <!-- 功能卡片 6 -->
                    <div class="bg-white rounded-xl shadow-card hover:shadow-card-hover p-6 transition-all duration-300 hover:-translate-y-1">
                        <div class="w-12 h-12 rounded-lg bg-primary/10 flex items-center justify-center mb-4">
                            <i class="fa fa-code-fork text-primary text-xl"></i>
                        </div>
                        <h3 class="text-xl font-semibold mb-3">包支持</h3>
                        <p class="text-dark-2">支持编译包含多个模块的Python包，自动处理模块间的依赖关系。</p>
                    </div>
                </div>
            </div>
        </section>
        
        <!-- 编译器区域 -->
        <section id="compiler" class="py-16 bg-light-1">
            <div class="container mx-auto px-4 sm:px-6 lg:px-8">
                <div class="text-center mb-12">
                    <h2 class="text-3xl font-bold mb-4">Python 到 二进制模块编译器</h2>
                    <p class="text-dark-2 max-w-2xl mx-auto">上传您的Python文件，配置编译选项，一键生成二进制模块</p>
                </div>
                
                <div class="max-w-5xl mx-auto bg-white rounded-2xl shadow-card overflow-hidden">
                    <div class="grid grid-cols-1 lg:grid-cols-3 divide-y lg:divide-y-0 lg:divide-x divide-light-2">
                        <!-- 左侧：配置选项 -->
                        <div class="p-6 lg:col-span-1">
                            <h3 class="text-xl font-semibold mb-6 flex items-center">
                                <i class="fa fa-cog text-primary mr-2"></i> 编译配置
                            </h3>
                            
                            <form id="compiler-form" class="space-y-6">
                                <!-- 优化级别 -->
                                <div>
                                    <label class="block text-sm font-medium text-dark mb-2">优化级别</label>
                                    <select name="optimize" class="w-full px-4 py-2 border border-light-2 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-colors">
                                        <option value="0">0 - 无优化</option>
                                        <option value="1">1 - 基础优化</option>
                                        <option value="2" selected>2 - 额外优化</option>
                                        <option value="3">3 - 最高优化</option>
                                    </select>
                                    <p class="text-xs text-dark-2 mt-1">更高的优化级别可能会提高性能，但编译时间更长</p>
                                </div>
                                
                                <!-- Python版本 -->
                                <div>
                                    <label class="block text-sm font-medium text-dark mb-2">Python版本</label>
                                    <select name="python-version" class="w-full px-4 py-2 border border-light-2 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-colors">
                                        <option value="2">Python 2.x</option>
                                        <option value="3" selected>Python 3.x</option>
                                    </select>
                                </div>
                                
                                <!-- 平台选择 -->
                                <div>
                                    <label class="block text-sm font-medium text-dark mb-2">目标平台</label>
                                    <div class="grid grid-cols-3 gap-2">
                                        <label class="flex flex-col items-center p-3 border border-light-2 rounded-lg cursor-pointer hover:border-primary transition-colors">
                                            <input type="radio" name="platform" value="linux" class="sr-only peer" checked>
                                            <i class="fa fa-linux text-xl mb-1 peer-checked:text-primary"></i>
                                            <span class="text-sm peer-checked:text-primary">Linux</span>
                                        </label>
                                        <label class="flex flex-col items-center p-3 border border-light-2 rounded-lg cursor-pointer hover:border-primary transition-colors">
                                            <input type="radio" name="platform" value="windows" class="sr-only peer">
                                            <i class="fa fa-windows text-xl mb-1 peer-checked:text-primary"></i>
                                            <span class="text-sm peer-checked:text-primary">Windows</span>
                                        </label>
                                        <label class="flex flex-col items-center p-3 border border-light-2 rounded-lg cursor-pointer hover:border-primary transition-colors">
                                            <input type="radio" name="platform" value="macos" class="sr-only peer">
                                            <i class="fa fa-apple text-xl mb-1 peer-checked:text-primary"></i>
                                            <span class="text-sm peer-checked:text-primary">macOS</span>
                                        </label>
                                    </div>
                                </div>
                                
                                <!-- 输出设置 -->
                                <div>
                                    <label class="block text-sm font-medium text-dark mb-2">输出设置</label>
                                    <div class="space-y-3">
                                        <div class="flex items-center">
                                            <input type="checkbox" id="keep-source" name="keep-source" class="w-4 h-4 text-primary rounded border-light-2 focus:ring-primary">
                                            <label for="keep-source" class="ml-2 text-sm text-dark-2">保留源文件</label>
                                        </div>
                                        <div class="flex items-center">
                                            <input type="checkbox" id="zip-output" name="zip-output" class="w-4 h-4 text-primary rounded border-light-2 focus:ring-primary">
                                            <label for="zip-output" class="ml-2 text-sm text-dark-2">压缩输出文件</label>
                                        </div>
                                        <div class="flex items-center">
                                            <input type="checkbox" id="delete-temp" name="delete-temp" checked class="w-4 h-4 text-primary rounded border-light-2 focus:ring-primary">
                                            <label for="delete-temp" class="ml-2 text-sm text-dark-2">删除临时文件</label>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- 高级选项 -->
                                <div>
                                    <button type="button" id="advanced-toggle" class="text-primary text-sm flex items-center">
                                        高级选项 <i class="fa fa-chevron-down ml-1 transition-transform duration-300"></i>
                                    </button>
                                    <div id="advanced-options" class="mt-4 space-y-4 hidden">
                                        <div>
                                            <label class="block text-xs font-medium text-dark mb-1">额外编译参数</label>
                                            <input type="text" name="extra-args" placeholder="-DCFLAGS=-O3" class="w-full px-3 py-2 text-sm border border-light-2 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-colors">
                                        </div>
                                        <div>
                                            <label class="block text-xs font-medium text-dark mb-1">输出目录</label>
                                            <input type="text" name="output-dir" placeholder="dist/" class="w-full px-3 py-2 text-sm border border-light-2 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-colors">
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- 编译按钮 -->
                                <button type="button" id="compile-button" class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-3 px-4 rounded-lg transition-all shadow-md hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-primary">
                                    <i class="fa fa-play mr-2"></i> 开始编译
                                </button>
                            </form>
                        </div>
                        
                        <!-- 右侧：文件上传和结果 -->
                        <div class="p-6 lg:col-span-2">
                            <!-- 上传区域 -->
                            <div id="upload-area" class="border-2 border-dashed border-light-2 rounded-xl p-8 text-center transition-all duration-300 hover:border-primary/50 mb-6">
                                <div class="max-w-md mx-auto">
                                    <div class="w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mx-auto mb-4">
                                        <i class="fa fa-cloud-upload text-primary text-2xl"></i>
                                    </div>
                                    <h3 class="text-lg font-medium mb-2">上传Python文件</h3>
                                    <p class="text-dark-2 text-sm mb-4">支持单个或多个.py文件，或包含多个模块的.zip包</p>
                                    
                                    <label class="inline-block bg-white border border-light-2 hover:border-primary text-primary font-medium py-2 px-6 rounded-lg transition-all cursor-pointer mb-4">
                                        <i class="fa fa-folder-open mr-2"></i> 选择文件
                                        <input type="file" id="file-upload" accept=".py,.zip" multiple class="hidden">
                                    </label>
                                    
                                    <p class="text-xs text-dark-2">或者直接将文件拖放到此处</p>
                                </div>
                            </div>
                            
                            <!-- 已上传文件列表 -->
                            <div id="file-list-container" class="mb-6 hidden">
                                <h3 class="text-lg font-medium mb-3 flex items-center">
                                    <i class="fa fa-files-o text-primary mr-2"></i> 已上传文件
                                    <span id="file-count" class="ml-2 bg-primary/10 text-primary text-xs px-2 py-1 rounded-full">0个文件</span>
                                </h3>
                                <div id="file-list" class="space-y-2 max-h-40 overflow-y-auto scrollbar-hide pr-2">
                                    <!-- 文件列表将在这里动态生成 -->
                                </div>
                            </div>
                            
                            <!-- 编译进度 -->
                            <div id="progress-container" class="mb-6 hidden">
                                <h3 class="text-lg font-medium mb-3 flex items-center">
                                    <i class="fa fa-spinner fa-spin text-primary mr-2"></i> 编译进度
                                </h3>
                                <div class="bg-light-1 rounded-full h-2.5 mb-2">
                                    <div id="progress-bar" class="bg-primary h-2.5 rounded-full w-0 transition-all duration-300"></div>
                                </div>
                                <div class="flex justify-between text-sm">
                                    <span id="progress-text">准备中...</span>
                                    <span id="progress-percentage">0%</span>
                                </div>
                                
                                <!-- 编译日志 -->
                                <div class="mt-4 bg-dark/5 rounded-lg p-3 text-sm text-dark-2 max-h-40 overflow-y-auto font-mono">
                                    <pre id="compile-log"></pre>
                                </div>
                            </div>
                            
                            <!-- 编译结果 -->
                            <div id="result-container" class="mb-6 hidden">
                                <h3 class="text-lg font-medium mb-3 flex items-center">
                                    <i class="fa fa-check-circle text-success mr-2"></i> 编译结果
                                </h3>
                                <div id="success-result" class="hidden">
                                    <div class="bg-success/10 border border-success/20 rounded-lg p-4 mb-4">
                                        <p class="text-success font-medium">编译成功！</p>
                                        <p class="text-sm text-dark-2 mt-1">您的文件已成功编译为二进制模块</p>
                                    </div>
                                    <div id="result-files" class="space-y-3 max-h-40 overflow-y-auto scrollbar-hide pr-2">
                                        <!-- 结果文件将在这里动态生成 -->
                                    </div>
                                </div>
                                <div id="error-result" class="hidden">
                                    <div class="bg-danger/10 border border-danger/20 rounded-lg p-4">
                                        <p class="text-danger font-medium">编译失败</p>
                                        <p class="text-sm text-dark-2 mt-1" id="error-message">请查看日志了解详细信息</p>
                                    </div>
                                </div>
                                <div class="flex justify-end space-x-3 mt-4">
                                    <button id="new-compile-button" class="px-4 py-2 border border-light-2 rounded-lg text-dark hover:bg-light-1 transition-colors">
                                        新的编译
                                    </button>
                                    <button id="download-all-button" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors hidden">
                                        <i class="fa fa-download mr-1"></i> 下载全部
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
        
        <!-- 历史记录 -->
        <section id="history" class="py-16 bg-white">
            <div class="container mx-auto px-4 sm:px-6 lg:px-8">
                <div class="text-center mb-12">
                    <h2 class="text-3xl font-bold mb-4">编译历史记录</h2>
                    <p class="text-dark-2 max-w-2xl mx-auto">查看您过往的编译记录，随时重新下载已编译的文件</p>
                </div>
                
                <div class="max-w-5xl mx-auto">
                    <div class="bg-white rounded-2xl shadow-card overflow-hidden">
                        <div class="p-6 border-b border-light-2">
                            <div class="flex justify-between items-center">
                                <h3 class="text-xl font-semibold">历史记录</h3>
                                <button id="clear-history" class="text-danger text-sm hover:underline">
                                    <i class="fa fa-trash-o mr-1"></i> 清空历史
                                </button>
                            </div>
                        </div>
                        
                        <div id="history-list" class="divide-y divide-light-2">
                            <!-- 历史记录为空状态 -->
                            <div id="empty-history" class="p-12 text-center">
                                <div class="w-16 h-16 rounded-full bg-light-1 flex items-center justify-center mx-auto mb-4">
                                    <i class="fa fa-history text-light-2 text-2xl"></i>
                                </div>
                                <p class="text-dark-2">暂无编译历史记录</p>
                                <p class="text-sm text-dark-2 mt-1">完成第一次编译后，记录将显示在这里</p>
                            </div>
                            
                            <!-- 历史记录将在这里动态生成 -->
                        </div>
                    </div>
                </div>
            </div>
        </section>
        
        <!-- 统计和图表 -->
        <section class="py-16 bg-light-1">
            <div class="container mx-auto px-4 sm:px-6 lg:px-8">
                <div class="text-center mb-12">
                    <h2 class="text-3xl font-bold mb-4">编译统计</h2>
                    <p class="text-dark-2 max-w-2xl mx-auto">查看您的编译活动和成功率统计</p>
                </div>
                
                <div class="max-w-5xl mx-auto grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- 统计卡片 -->
                    <div class="bg-white rounded-xl shadow-card p-6">
                        <h3 class="text-lg font-semibold mb-4">编译概览</h3>
                        <div class="grid grid-cols-2 gap-4">
                            <div class="bg-light-1 rounded-lg p-4 text-center">
                                <p class="text-dark-2 text-sm">总编译次数</p>
                                <p class="text-2xl font-bold text-dark mt-1" id="total-compilations">0</p>
                            </div>
                            <div class="bg-light-1 rounded-lg p-4 text-center">
                                <p class="text-dark-2 text-sm">成功次数</p>
                                <p class="text-2xl font-bold text-success mt-1" id="successful-compilations">0</p>
                            </div>
                            <div class="bg-light-1 rounded-lg p-4 text-center">
                                <p class="text-dark-2 text-sm">失败次数</p>
                                <p class="text-2xl font-bold text-danger mt-1" id="failed-compilations">0</p>
                            </div>
                            <div class="bg-light-1 rounded-lg p-4 text-center">
                                <p class="text-dark-2 text-sm">总文件数</p>
                                <p class="text-2xl font-bold text-primary mt-1" id="total-files">0</p>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 图表 -->
                    <div class="bg-white rounded-xl shadow-card p-6">
                        <h3 class="text-lg font-semibold mb-4">平台分布</h3>
                        <div class="h-64">
                            <canvas id="platform-chart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </section>
        
        <!-- 帮助区域 -->
        <section id="help" class="py-16 bg-white">
            <div class="container mx-auto px-4 sm:px-6 lg:px-8">
                <div class="text-center mb-12">
                    <h2 class="text-3xl font-bold mb-4">使用帮助</h2>
                    <p class="text-dark-2 max-w-2xl mx-auto">了解如何使用Py2SO工具将Python文件编译为二进制模块</p>
                </div>
                
                <div class="max-w-3xl mx-auto">
                    <!-- 常见问题 -->
                    <div class="space-y-4 mb-12">
                        <h3 class="text-xl font-semibold mb-6">常见问题</h3>
                        
                        <!-- FAQ 项目 -->
                        <div class="border border-light-2 rounded-lg overflow-hidden">
                            <button class="faq-toggle w-full flex justify-between items-center p-4 text-left bg-white hover:bg-light-1 transition-colors">
                                <span class="font-medium">什么是.so/.pyd文件？</span>
                                <i class="fa fa-chevron-down text-light-2 transition-transform duration-300"></i>
                            </button>
                            <div class="faq-content hidden p-4 pt-0 bg-white border-t border-light-2">
                                <p class="text-dark-2">.so文件是Linux和macOS系统上的共享对象文件，类似于Windows系统上的.dll文件。.pyd是Python专用的动态链接库文件，在Windows系统上使用。它们都是二进制文件，可以被Python解释器导入和使用，但无法直接查看源代码。</p>
                            </div>
                        </div>
                        
                        <div class="border border-light-2 rounded-lg overflow-hidden">
                            <button class="faq-toggle w-full flex justify-between items-center p-4 text-left bg-white hover:bg-light-1 transition-colors">
                                <span class="font-medium">编译后的文件可以在不同平台上使用吗？</span>
                                <i class="fa fa-chevron-down text-light-2 transition-transform duration-300"></i>
                            </button>
                            <div class="faq-content hidden p-4 pt-0 bg-white border-t border-light-2">
                                <p class="text-dark-2">不能。二进制模块是平台相关的，在Linux上编译的.so文件不能在Windows或macOS上使用，反之亦然。您需要为目标平台单独编译模块。</p>
                            </div>
                        </div>
                        
                        <div class="border border-light-2 rounded-lg overflow-hidden">
                            <button class="faq-toggle w-full flex justify-between items-center p-4 text-left bg-white hover:bg-light-1 transition-colors">
                                <span class="font-medium">编译后的模块性能会提升吗？</span>
                                <i class="fa fa-chevron-down text-light-2 transition-transform duration-300"></i>
                            </button>
                            <div class="faq-content hidden p-4 pt-0 bg-white border-t border-light-2">
                                <p class="text-dark-2">是的，在大多数情况下，编译为二进制模块可以提高代码的执行速度，尤其是对于计算密集型任务。您可以通过选择更高的优化级别来获得更好的性能，但编译时间也会相应增加。</p>
                            </div>
                        </div>
                        
                        <div class="border border-light-2 rounded-lg overflow-hidden">
                            <button class="faq-toggle w-full flex justify-between items-center p-4 text-left bg-white hover:bg-light-1 transition-colors">
                                <span class="font-medium">为什么我的文件编译失败？</span>
                                <i class="fa fa-chevron-down text-light-2 transition-transform duration-300"></i>
                            </button>
                            <div class="faq-content hidden p-4 pt-0 bg-white border-t border-light-2">
                                <p class="text-dark-2">编译失败可能有多种原因，包括：代码中存在语法错误、使用了不支持的Python特性、缺少依赖库等。您可以查看编译日志获取详细的错误信息，修复问题后重新尝试编译。</p>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 使用教程 -->
                    <div>
                        <h3 class="text-xl font-semibold mb-6">使用教程</h3>
                        <div class="space-y-6">
                            <div class="flex">
                                <div class="flex-shrink-0 w-8 h-8 rounded-full bg-primary flex items-center justify-center text-white font-medium mr-4">1</div>
                                <div>
                                    <h4 class="font-medium mb-2">上传Python文件</h4>
                                    <p class="text-dark-2">点击"选择文件"按钮或直接拖放，上传您想要编译的.py文件或包含多个模块的.zip包。</p>
                                </div>
                            </div>
                            
                            <div class="flex">
                                <div class="flex-shrink-0 w-8 h-8 rounded-full bg-primary flex items-center justify-center text-white font-medium mr-4">2</div>
                                <div>
                                    <h4 class="font-medium mb-2">配置编译选项</h4>
                                    <p class="text-dark-2">选择优化级别、Python版本和目标平台，根据需要设置其他选项，如是否保留源文件等。</p>
                                </div>
                            </div>
                            
                            <div class="flex">
                                <div class="flex-shrink-0 w-8 h-8 rounded-full bg-primary flex items-center justify-center text-white font-medium mr-4">3</div>
                                <div>
                                    <h4 class="font-medium mb-2">开始编译</h4>
                                    <p class="text-dark-2">点击"开始编译"按钮，等待编译完成。您可以在进度条下方查看详细的编译日志。</p>
                                </div>
                            </div>
                            
                            <div class="flex">
                                <div class="flex-shrink-0 w-8 h-8 rounded-full bg-primary flex items-center justify-center text-white font-medium mr-4">4</div>
                                <div>
                                    <h4 class="font-medium mb-2">下载结果</h4>
                                    <p class="text-dark-2">编译成功后，您可以下载生成的二进制模块文件。所有历史记录会保存在"历史记录"区域，方便日后查看和下载。</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <!-- 页脚 -->
    <footer class="bg-dark text-white py-12">
        <div class="container mx-auto px-4 sm:px-6 lg:px-8">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
                <div class="md:col-span-1">
                    <div class="flex items-center space-x-2 mb-4">
                        <div class="w-10 h-10 rounded-lg gradient-bg flex items-center justify-center">
                            <i class="fa fa-cogs text-white text-xl"></i>
                        </div>
                        <h2 class="text-xl font-bold">Py2SO</h2>
                    </div>
                    <p class="text-gray-400 text-sm">将Python文件转换为二进制模块的专业工具，保护您的源代码安全。</p>
                </div>
                
                <div>
                    <h3 class="text-lg font-medium mb-4">功能</h3>
                    <ul class="space-y-2 text-gray-400 text-sm">
                        <li><a href="#" class="hover:text-white transition-colors">文件编译</a></li>
                        <li><a href="#" class="hover:text-white transition-colors">批量处理</a></li>
                        <li><a href="#" class="hover:text-white transition-colors">包编译</a></li>
                        <li><a href="#" class="hover:text-white transition-colors">历史记录</a></li>
                    </ul>
                </div>
                
                <div>
                    <h3 class="text-lg font-medium mb-4">资源</h3>
                    <ul class="space-y-2 text-gray-400 text-sm">
                        <li><a href="#" class="hover:text-white transition-colors">使用文档</a></li>
                        <li><a href="#" class="hover:text-white transition-colors">API参考</a></li>
                        <li><a href="#" class="hover:text-white transition-colors">常见问题</a></li>
                        <li><a href="#" class="hover:text-white transition-colors">更新日志</a></li>
                    </ul>
                </div>
                
                <div>
                    <h3 class="text-lg font-medium mb-4">联系我们</h3>
                    <ul class="space-y-2 text-gray-400 text-sm">
                        <li class="flex items-center"><i class="fa fa-envelope-o mr-2"></i> support@py2so.com</li>
                        <li class="flex items-center"><i class="fa fa-github mr-2"></i> github.com/py2so</li>
                        <li class="flex items-center"><i class="fa fa-twitter mr-2"></i> @py2so</li>
                    </ul>
                    <div class="mt-4 flex space-x-4">
                        <a href="#" class="w-8 h-8 rounded-full bg-gray-800 flex items-center justify-center hover:bg-primary transition-colors">
                            <i class="fa fa-github"></i>
                        </a>
                        <a href="#" class="w-8 h-8 rounded-full bg-gray-800 flex items-center justify-center hover:bg-primary transition-colors">
                            <i class="fa fa-twitter"></i>
                        </a>
                        <a href="#" class="w-8 h-8 rounded-full bg-gray-800 flex items-center justify-center hover:bg-primary transition-colors">
                            <i class="fa fa-linkedin"></i>
                        </a>
                    </div>
                </div>
            </div>
            
            <div class="border-t border-gray-800 mt-8 pt-8 flex flex-col md:flex-row justify-between items-center">
                <p class="text-gray-400 text-sm">© 2023 Py2SO. 保留所有权利。</p>
                <div class="flex space-x-6 mt-4 md:mt-0">
                    <a href="#" class="text-gray-400 text-sm hover:text-white transition-colors">隐私政策</a>
                    <a href="#" class="text-gray-400 text-sm hover:text-white transition-colors">服务条款</a>
                    <a href="#" class="text-gray-400 text-sm hover:text-white transition-colors">Cookie政策</a>
                </div>
            </div>
        </div>
    </footer>

    <!-- JavaScript -->
    <script>
        // DOM 元素
        const mobileMenuButton = document.getElementById('mobile-menu-button');
        const mobileMenu = document.getElementById('mobile-menu');
        const themeToggle = document.getElementById('theme-toggle');
        const advancedToggle = document.getElementById('advanced-toggle');
        const advancedOptions = document.getElementById('advanced-options');
        const fileUpload = document.getElementById('file-upload');
        const uploadArea = document.getElementById('upload-area');
        const fileListContainer = document.getElementById('file-list-container');
        const fileList = document.getElementById('file-list');
        const fileCount = document.getElementById('file-count');
        const compileButton = document.getElementById('compile-button');
        const progressContainer = document.getElementById('progress-container');
        const progressBar = document.getElementById('progress-bar');
        const progressText = document.getElementById('progress-text');
        const progressPercentage = document.getElementById('progress-percentage');
        const compileLog = document.getElementById('compile-log');
        const resultContainer = document.getElementById('result-container');
        const successResult = document.getElementById('success-result');
        const errorResult = document.getElementById('error-result');
        const errorMessage = document.getElementById('error-message');
        const resultFiles = document.getElementById('result-files');
        const newCompileButton = document.getElementById('new-compile-button');
        const downloadAllButton = document.getElementById('download-all-button');
        const historyList = document.getElementById('history-list');
        const emptyHistory = document.getElementById('empty-history');
        const clearHistoryButton = document.getElementById('clear-history');
        const faqToggles = document.querySelectorAll('.faq-toggle');
        const mainHeader = document.getElementById('main-header');
        
        // 统计元素
        const totalCompilationsEl = document.getElementById('total-compilations');
        const successfulCompilationsEl = document.getElementById('successful-compilations');
        const failedCompilationsEl = document.getElementById('failed-compilations');
        const totalFilesEl = document.getElementById('total-files');
        
        // 存储变量
        let uploadedFiles = [];
        let currentCompileId = null;
        let compilationStats = {
            total: 0,
            successful: 0,
            failed: 0,
            totalFiles: 0,
            platformDistribution: {
                linux: 0,
                windows: 0,
                macos: 0
            }
        };
        
        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            loadStats();
            loadHistory();
            initChart();
            setupEventListeners();
        });
        
        // 设置事件监听器
        function setupEventListeners() {
            // 移动端菜单切换
            mobileMenuButton.addEventListener('click', () => {
                mobileMenu.classList.toggle('hidden');
            });
            
            // 高级选项切换
            advancedToggle.addEventListener('click', () => {
                advancedOptions.classList.toggle('hidden');
                const icon = advancedToggle.querySelector('i');
                icon.classList.toggle('rotate-180');
            });
            
            // 文件上传
            fileUpload.addEventListener('change', handleFileSelect);
            
            // 拖放功能
            uploadArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                uploadArea.classList.add('border-primary');
                uploadArea.classList.add('bg-primary/5');
            });
            
            uploadArea.addEventListener('dragleave', () => {
                uploadArea.classList.remove('border-primary');
                uploadArea.classList.remove('bg-primary/5');
            });
            
            uploadArea.addEventListener('drop', (e) => {
                e.preventDefault();
                uploadArea.classList.remove('border-primary');
                uploadArea.classList.remove('bg-primary/5');
                
                if (e.dataTransfer.files.length) {
                    handleFiles(e.dataTransfer.files);
                }
            });
            
            // 编译按钮
            compileButton.addEventListener('click', startCompilation);
            
            // 新的编译按钮
            newCompileButton.addEventListener('click', resetCompiler);
            
            // 清空历史记录
            clearHistoryButton.addEventListener('click', clearHistory);
            
            // FAQ 切换
            faqToggles.forEach(toggle => {
                toggle.addEventListener('click', () => {
                    const content = toggle.nextElementSibling;
                    const icon = toggle.querySelector('i');
                    
                    content.classList.toggle('hidden');
                    icon.classList.toggle('rotate-180');
                });
            });
            
            // 滚动时导航栏效果
            window.addEventListener('scroll', () => {
                if (window.scrollY > 50) {
                    mainHeader.classList.add('shadow');
                } else {
                    mainHeader.classList.remove('shadow');
                }
            });
        }
        
        // 处理文件选择
        function handleFileSelect(e) {
            handleFiles(e.target.files);
        }
        
        // 处理文件
        function handleFiles(files) {
            // 过滤非.py和非.zip文件
            const validFiles = Array.from(files).filter(file => 
                file.name.endsWith('.py') || file.name.endsWith('.zip')
            );
            
            if (validFiles.length === 0) {
                alert('请选择.py文件或包含Python模块的.zip包');
                return;
            }
            
            // 添加到上传文件列表
            validFiles.forEach(file => {
                // 检查是否已存在相同文件
                const exists = uploadedFiles.some(f => 
                    f.name === file.name && f.size === file.size
                );
                
                if (!exists) {
                    uploadedFiles.push(file);
                }
            });
            
            // 更新文件列表显示
            updateFileList();
            
            // 启用编译按钮
            compileButton.disabled = false;
        }
        
        // 更新文件列表显示
        function updateFileList() {
            if (uploadedFiles.length === 0) {
                fileListContainer.classList.add('hidden');
                return;
            }
            
            fileListContainer.classList.remove('hidden');
            fileCount.textContent = `${uploadedFiles.length}个文件`;
            fileList.innerHTML = '';
            
            uploadedFiles.forEach((file, index) => {
                const fileSize = formatFileSize(file.size);
                const fileType = file.name.endsWith('.py') ? 'python' : 'zip';
                
                const fileItem = document.createElement('div');
                fileItem.className = 'flex items-center justify-between p-3 bg-light-1 rounded-lg';
                fileItem.innerHTML = `
                    <div class="flex items-center">
                        <i class="fa fa-${fileType}-file-o text-primary mr-3"></i>
                        <div>
                            <p class="text-sm font-medium truncate max-w-[200px] sm:max-w-[300px]">${file.name}</p>
                            <p class="text-xs text-dark-2">${fileSize}</p>
                        </div>
                    </div>
                    <button class="text-dark-2 hover:text-danger transition-colors delete-file" data-index="${index}">
                        <i class="fa fa-trash-o"></i>
                    </button>
                `;
                
                fileList.appendChild(fileItem);
            });
            
            // 添加删除文件事件
            document.querySelectorAll('.delete-file').forEach(button => {
                button.addEventListener('click', (e) => {
                    const index = parseInt(e.currentTarget.dataset.index);
                    uploadedFiles.splice(index, 1);
                    updateFileList();
                    
                    if (uploadedFiles.length === 0) {
                        compileButton.disabled = true;
                    }
                });
            });
        }
        
        // 开始编译
        function startCompilation() {
            if (uploadedFiles.length === 0) {
                return;
            }
            
            // 获取表单数据
            const formData = new FormData(document.getElementById('compiler-form'));
            
            // 添加上传的文件
            uploadedFiles.forEach(file => {
                formData.append('files', file);
            });
            
            // 显示进度区域
            fileListContainer.classList.add('hidden');
            progressContainer.classList.remove('hidden');
            progressBar.style.width = '0%';
            progressPercentage.textContent = '0%';
            progressText.textContent = '正在上传文件...';
            compileLog.textContent = '';
            
            // 禁用编译按钮
            compileButton.disabled = true;
            
            // 调用后端编译API
            fetch('/api/compile/start', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                currentCompileId = data.task_id;
                progressText.textContent = '编译任务已启动，正在处理...';
                compileLog.textContent = `[INFO] 编译任务已启动: ${data.task_id}\n`;
                
                // 开始轮询编译状态
                pollCompilationStatus(data.task_id);
            })
            .catch(error => {
                console.error('启动编译失败:', error);
                progressText.textContent = '编译启动失败';
                compileLog.textContent = `[ERROR] 启动编译失败: ${error.message}\n`;
                
                // 显示错误结果
                handleCompilationFailure(`启动编译失败: ${error.message}`);
            });
        }
        
        // 轮询编译状态
        function pollCompilationStatus(taskId) {
            const pollInterval = setInterval(() => {
                fetch(`/api/compile/status/${taskId}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(statusData => {
                    // 更新进度显示
                    const progress = statusData.progress || 0;
                    progressBar.style.width = `${progress}%`;
                    progressPercentage.textContent = `${progress}%`;
                    progressText.textContent = statusData.message || '正在编译...';
                    
                    // 更新日志
                    if (statusData.logs && statusData.logs.length > 0) {
                        compileLog.textContent = statusData.logs.join('\n') + '\n';
                        compileLog.scrollTop = compileLog.scrollHeight;
                    }
                    
                    // 检查编译状态
                    if (statusData.status === 'success') {
                        clearInterval(pollInterval);
                        handleCompilationSuccess(statusData);
                    } else if (statusData.status === 'failed') {
                        clearInterval(pollInterval);
                        handleCompilationFailure(statusData.error || '编译失败');
                    }
                })
                .catch(error => {
                    console.error('获取编译状态失败:', error);
                    clearInterval(pollInterval);
                    handleCompilationFailure(`获取编译状态失败: ${error.message}`);
                });
            }, 2000); // 每2秒轮询一次
        }
        
        // 处理编译成功
        function handleCompilationSuccess(resultData) {
            // 获取编译结果详情
            fetch(`/api/compile/result/${currentCompileId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(result => {
                // 显示结果
                progressContainer.classList.add('hidden');
                resultContainer.classList.remove('hidden');
                successResult.classList.remove('hidden');
                errorResult.classList.add('hidden');
                resultFiles.innerHTML = '';
                
                // 添加结果文件到显示
                if (result.output_files && result.output_files.length > 0) {
                    result.output_files.forEach(file => {
                        const fileSize = formatFileSize(file.filesize || 0);
                        
                        const fileItem = document.createElement('div');
                        fileItem.className = 'flex items-center justify-between p-3 bg-light-1 rounded-lg';
                        fileItem.innerHTML = `
                            <div class="flex items-center">
                                <i class="fa fa-file-code-o text-success mr-3"></i>
                                <div>
                                    <p class="text-sm font-medium">${file.filename}</p>
                                    <p class="text-xs text-dark-2">文件大小: ${fileSize}</p>
                                </div>
                            </div>
                            <button class="text-primary hover:text-primary/80 transition-colors download-file" data-name="${file.filename}" data-task-id="${currentCompileId}">
                                <i class="fa fa-download mr-1"></i> 下载
                            </button>
                        `;
                        
                        resultFiles.appendChild(fileItem);
                    });
                    
                    // 添加下载事件
                    document.querySelectorAll('.download-file').forEach(button => {
                        button.addEventListener('click', (e) => {
                            const fileName = e.currentTarget.dataset.name;
                            const taskId = e.currentTarget.dataset.taskId;
                            downloadFile(fileName, taskId);
                        });
                    });
                    
                    // 显示下载全部按钮
                    downloadAllButton.classList.remove('hidden');
                    downloadAllButton.dataset.taskId = currentCompileId;
                    downloadAllButton.addEventListener('click', () => {
                        downloadAllFiles(currentCompileId);
                    });
                } else {
                    // 没有结果文件的情况
                    const noFilesItem = document.createElement('div');
                    noFilesItem.className = 'text-center p-4 text-dark-2';
                    noFilesItem.textContent = '编译成功，但没有生成结果文件';
                    resultFiles.appendChild(noFilesItem);
                }
                
                // 保存到历史记录
                saveToHistory({
                    id: currentCompileId,
                    timestamp: new Date().toISOString(),
                    files: uploadedFiles.map(f => ({ name: f.name, size: f.size })),
                    resultFiles: result.output_files || [],
                    options: result.options || {},
                    success: true
                });
            })
            .catch(error => {
                console.error('获取编译结果失败:', error);
                handleCompilationFailure(`获取编译结果失败: ${error.message}`);
            });
        }
        
        // 处理编译失败
        function handleCompilationFailure(errorMessage) {
            // 显示错误结果
            progressContainer.classList.add('hidden');
            resultContainer.classList.remove('hidden');
            successResult.classList.add('hidden');
            errorResult.classList.remove('hidden');
            
            // 设置错误消息
            const errorMessageElement = errorResult.querySelector('.text-danger');
            if (errorMessageElement) {
                errorMessageElement.textContent = errorMessage || '编译过程中出现错误';
            }
            
            // 保存到历史记录
            saveToHistory({
                id: currentCompileId,
                timestamp: new Date().toISOString(),
                files: uploadedFiles.map(f => ({ name: f.name, size: f.size })),
                success: false,
                error: errorMessage || '编译过程中出现错误'
            });
        }
        
        // 重置编译器
        function resetCompiler() {
            // 清空上传文件
            uploadedFiles = [];
            updateFileList();
            
            // 重置表单状态
            document.getElementById('compiler-form').reset();
            
            // 重置UI
            resultContainer.classList.add('hidden');
            progressContainer.classList.add('hidden');
            fileListContainer.classList.add('hidden');
            downloadAllButton.classList.add('hidden');
            
            // 启用编译按钮
            compileButton.disabled = false;
        }
        
        // 下载文件
        function downloadFile(fileName, taskId) {
            // 使用后端API下载文件
            const downloadUrl = `/api/compile/download/${taskId || currentCompileId}/${encodeURIComponent(fileName)}`;
            const a = document.createElement('a');
            a.href = downloadUrl;
            a.download = fileName;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            
            // 显示下载成功提示
            showNotification(`文件 ${fileName} 下载成功`, 'success');
        }
        
        // 下载所有文件
        function downloadAllFiles(taskId) {
            // 使用后端API下载所有文件
            const downloadUrl = `/api/compile/download-all/${taskId || currentCompileId}`;
            const a = document.createElement('a');
            a.href = downloadUrl;
            a.download = 'compiled_files.zip';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            
            // 显示下载成功提示
            showNotification('所有文件下载成功', 'success');
        }
        
        // 保存到历史记录
        function saveToHistory(record) {
            let history = JSON.parse(localStorage.getItem('py2so_history') || '[]');
            
            // 添加新记录到开头
            history.unshift(record);
            
            // 限制历史记录数量
            if (history.length > 20) {
                history = history.slice(0, 20);
            }
            
            // 保存到本地存储
            localStorage.setItem('py2so_history', JSON.stringify(history));
            
            // 更新历史记录显示
            loadHistory();
        }
        
        // 加载历史记录
        function loadHistory() {
            // 从后端API获取历史记录
            fetch('/api/history/')
                .then(response => response.json())
                .then(data => {
                    const history = data.history || [];
                    
                    if (history.length === 0) {
                        emptyHistory.classList.remove('hidden');
                        historyList.appendChild(emptyHistory);
                        return;
                    }
                    
                    // 隐藏空状态
                    if (emptyHistory.parentNode === historyList) {
                        historyList.removeChild(emptyHistory);
                    }
                    
                    // 清空现有历史记录（保留空状态以外的内容）
                    while (historyList.firstChild) {
                        if (historyList.firstChild === emptyHistory) {
                            break;
                        }
                        historyList.removeChild(historyList.firstChild);
                    }
                    
                    // 添加历史记录
                    history.forEach(record => {
                        const date = new Date(record.created_at);
                        const formattedDate = date.toLocaleString();
                        
                        const historyItem = document.createElement('div');
                        historyItem.className = 'p-6 hover:bg-light-1 transition-colors';
                        historyItem.innerHTML = `
                            <div class="flex justify-between items-start mb-3">
                                <div>
                                    <h4 class="font-medium">${record.status === 'completed' ? '编译成功' : '编译失败'}</h4>
                                    <p class="text-sm text-dark-2">${formattedDate}</p>
                                </div>
                                <span class="px-2 py-1 rounded-full text-xs ${record.status === 'completed' ? 'bg-success/10 text-success' : 'bg-danger/10 text-danger'}">
                                    ${record.status === 'completed' ? '成功' : '失败'}
                                </span>
                            </div>
                            
                            <div class="mb-4">
                                <p class="text-sm font-medium mb-2">处理的文件 (${record.files ? record.files.length : 0}个)</p>
                                <div class="flex flex-wrap gap-2">
                                    ${record.files ? record.files.map(file => `
                                        <span class="bg-light-1 text-dark-2 text-xs px-2 py-1 rounded">
                                            ${file.filename}
                                        </span>
                                    `).join('') : ''}
                                </div>
                            </div>
                            
                            ${record.status === 'completed' ? `
                            <div class="mb-4">
                                <p class="text-sm font-medium mb-2">生成的文件</p>
                                <div class="flex flex-wrap gap-2">
                                    <span class="bg-light-1 text-dark-2 text-xs px-2 py-1 rounded flex items-center">
                                        ${record.output_files && record.output_files.length > 0 ? record.output_files[0].filename : '编译结果'}
                                        <button class="ml-1 text-primary download-history-file" data-name="${record.output_files && record.output_files.length > 0 ? record.output_files[0].filename : 'output'}" data-task-id="${record.task_id}">
                                            <i class="fa fa-download"></i>
                                        </button>
                                    </span>
                                </div>
                            </div>
                            ` : `
                            <div class="mb-4 p-3 bg-danger/10 rounded-lg text-sm text-danger">
                                <i class="fa fa-exclamation-circle mr-1"></i> ${record.error_message || '编译失败'}
                            </div>
                            `}
                            
                            <div class="text-sm text-dark-2">
                                <p>平台: ${formatPlatform(record.platform)}</p>
                                <p>优化级别: ${record.optimize_level}</p>
                                <p>Python版本: ${record.python_version}.x</p>
                            </div>
                        `;
                        
                        historyList.appendChild(historyItem);
                    });
                    
                    // 添加历史记录中的下载事件
                    document.querySelectorAll('.download-history-file').forEach(button => {
                        button.addEventListener('click', (e) => {
                            e.stopPropagation();
                            const fileName = e.currentTarget.dataset.name;
                            const taskId = e.currentTarget.dataset.taskId;
                            downloadFile(fileName, taskId);
                        });
                    });
                })
                .catch(error => {
                    console.error('获取历史记录失败:', error);
                    // 如果后端API失败，回退到本地存储
                    const localHistory = JSON.parse(localStorage.getItem('py2so_history') || '[]');
                    if (localHistory.length === 0) {
                        emptyHistory.classList.remove('hidden');
                        historyList.appendChild(emptyHistory);
                    }
                });
        }
        
        // 清空历史记录
        function clearHistory() {
            if (confirm('确定要清空所有历史记录吗？此操作不可恢复。')) {
                // 调用后端API删除所有历史记录
                fetch('/api/history/', { method: 'DELETE' })
                    .then(response => {
                        if (response.ok) {
                            // 同时清除本地存储
                            localStorage.removeItem('py2so_history');
                            loadHistory();
                        } else {
                            alert('清空历史记录失败，请重试。');
                        }
                    })
                    .catch(error => {
                        console.error('清空历史记录失败:', error);
                        alert('清空历史记录失败，请重试。');
                    });
            }
        }
        
        // 加载统计数据
        function loadStats() {
            // 从后端API获取统计数据
            fetch('/api/stats/')
                .then(response => response.json())
                .then(data => {
                    compilationStats = {
                        total: data.total_compilations || 0,
                        successful: data.successful_compilations || 0,
                        failed: data.failed_compilations || 0,
                        totalFiles: data.total_files || 0,
                        platformDistribution: {
                            linux: data.platform_distribution?.linux || 0,
                            windows: data.platform_distribution?.windows || 0,
                            macos: data.platform_distribution?.macos || 0
                        }
                    };
                    updateStatsDisplay();
                    updateChart();
                })
                .catch(error => {
                    console.error('获取统计数据失败:', error);
                    // 如果后端API失败，回退到本地存储
                    const savedStats = localStorage.getItem('py2so_stats');
                    if (savedStats) {
                        compilationStats = JSON.parse(savedStats);
                        updateStatsDisplay();
                        updateChart();
                    }
                });
        }
        
        // 保存统计数据（现在通过后端API自动保存）
        function saveStats() {
            // 统计数据现在通过后端API自动更新
            updateStatsDisplay();
            updateChart();
        }
        
        // 更新统计显示
        function updateStatsDisplay() {
            totalCompilationsEl.textContent = compilationStats.total;
            successfulCompilationsEl.textContent = compilationStats.successful;
            failedCompilationsEl.textContent = compilationStats.failed;
            totalFilesEl.textContent = compilationStats.totalFiles;
        }
        
        // 初始化图表
        let platformChart = null;
        function initChart() {
            const ctx = document.getElementById('platform-chart').getContext('2d');
            
            platformChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: ['Linux', 'Windows', 'macOS'],
                    datasets: [{
                        data: [
                            compilationStats.platformDistribution.linux,
                            compilationStats.platformDistribution.windows,
                            compilationStats.platformDistribution.macos
                        ],
                        backgroundColor: [
                            '#165DFF',
                            '#FAAD14',
                            '#52C41A'
                        ],
                        borderWidth: 0
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    },
                    cutout: '65%'
                }
            });
        }
        
        // 更新图表
        function updateChart() {
            if (platformChart) {
                platformChart.data.datasets[0].data = [
                    compilationStats.platformDistribution.linux,
                    compilationStats.platformDistribution.windows,
                    compilationStats.platformDistribution.macos
                ];
                platformChart.update();
            }
        }
        
        // 工具函数：格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
        
        // 工具函数：格式化平台名称
        function formatPlatform(platform) {
            switch(platform) {
                case 'linux': return 'Linux';
                case 'windows': return 'Windows';
                case 'macos': return 'macOS';
                default: return platform;
            }
        }
    </script>
</body>
</html>
